#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <fcntl.h>
#include <string>
#include <cstring>

const std::string pathname = "/home/csj/109/linux/lesson03/shm";
const int proj_id = 0x11223344;

const int ssize = 4096;

const std::string filename = "fifo";
key_t getkey()
{
    // 使用ftok算法计算出key值
    key_t key = ftok(pathname.c_str(), proj_id);
    if (key < 0)
    {
        std::cerr << "errno: " << errno << ". errstring" << strerror(errno) << std::endl;
        exit(-1);
    }
    return key;
}

// 十进制转十六进制
std::string ToHex(int id)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", id);
    return buffer;
}

int ShmHelper(int key, int flag)
{
    int shmid = shmget(key, ssize, flag);
    if (shmid < 0)
    {
        std::cerr << "errno: " << errno << ". errstring" << strerror(errno) << std::endl;
        exit(2);
    }
    return shmid;
}

int CreateShm(int key)
{
    return ShmHelper(key, IPC_CREAT | IPC_EXCL | 0644);
}

int GetShm(int key)
{
    return ShmHelper(key, IPC_CREAT);
}

bool makefifo()
{
    // 1.创建命名管道文件
    int n = mkfifo(filename.c_str(), 0666);
    if (n < 0)
    {
        std::cerr << "errno: " << errno << ". errstring" << strerror(errno) << std::endl;
        return false;
    }
    std::cout << "mkfifo success...." << std::endl;
    return true;
}